package com.moli.java.map.hashMap;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: JavaQuesDemo
 * @description: 线程安全的集合
 * @author: zhangjt
 * @create: 2024-11-19 10:57
 **/
public class ThreadSafeMap {
    /*
    * ConcurrentHashMap：这是 Java 提供的线程安全的 Map 实现，它通过分段锁（segment lock）来提高并发性能。
      Collections.synchronizedMap()：将普通的 HashMap 包装成线程安全的 Map。
    * */
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> stringIntegerConcurrentHashMap = new ConcurrentHashMap<>();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                stringIntegerConcurrentHashMap.put("key" + i, i);
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                stringIntegerConcurrentHashMap.put("key" + i + 1000, i);
            }
        });
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(stringIntegerConcurrentHashMap.size());
    }
}
